#include "treenode.h"
#include <string>
#include <cmath>


TreeNode::TreeNode(){}
TreeNode::TreeNode(float value): op(std::string("val")), val_num(value), var(false){}
TreeNode::TreeNode(std::string value): op(std::string("val")), val_str(value), var(true){}

float TreeNode::calc(std::map<std::string, float> table)
{
    if(op == "val") //常值节点
    {
        if(var) return table[val_str];
        else return val_num;
    }
    else
    {
        if(op == "+") return childs["num1"]->calc(table) + childs["num2"]->calc(table);
        if(op == "-") return childs["num1"]->calc(table) - childs["num2"]->calc(table);
        if(op == "*") return childs["num1"]->calc(table) * childs["num2"]->calc(table);
        if(op == "/") return childs["num1"]->calc(table) / childs["num2"]->calc(table);
        if(op == "^") return pow(childs["num1"]->calc(table), childs["num2"]->calc(table));
        if(op == "sin") return sin(childs["num"]->calc(table));
        if(op == "cos") return sin(childs["num"]->calc(table));
        if(op == "tan") return sin(childs["num"]->calc(table));
    }
    return 0;
}
